package com.zy.system.controller;



import com.zy.common.result.Result;
import com.zy.common.utils.JwtHelper;
import com.zy.common.utils.MD5;
import com.zy.model.system.SysUser;
import com.zy.model.vo.LoginVo;
import com.zy.system.exception.ZyException;
import com.zy.system.service.SysUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {

        SysUser sysUser = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        if(sysUser == null){
            throw new ZyException(20001,"用户不存");
        }
         //判断密码是否一致
        String password = loginVo.getPassword( );
        String md5Password = MD5.encrypt(password);
        if( ! sysUser.getPassword( ).equals(md5Password)) {
            throw new ZyException( 20001,"密码不正确");
        }
//判断用户是否可用
        if(sysUser.getStatus().intValue() == 0) {
            throw new ZyException(20001, "用户已经被禁用");
        }
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("roles","[admin]");
//        map.put("name","admin zy");
//        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        String token = request.getHeader("token");
        //从token字符串获取用户名称（id)
        String username = JwtHelper.getUsername(token) ;
        //根据用户名称获取用户信息（基本信息和菜单权限和按钮权限数据)Map<String,object> map = sysUserService.getUserInfo(username) ;
        Map<String, Object> userInfo = sysUserService.getUserInfo(username);
        return Result.ok(userInfo);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }

}